#pragma once
#include "stdafx.h"
#include "mySQLClass.h"

mySQLClass stc_SQL;

mySQLClass::mySQLClass()
{
	m_Port = 0;
	m_IsRuning = false;

	memset(m_HostName, 0, sizeof(m_HostName));
	memset(m_DBName, 0, sizeof(m_DBName));
	memset(m_Account, 0, sizeof(m_Account));
	memset(m_Password, 0, sizeof(m_Password));

	memset(&m_SQL, 0, sizeof(m_SQL));
	mysql_init(&m_SQL);
	mysql_options(&m_SQL, MYSQL_SET_CHARSET_NAME, "gbk");
}

mySQLClass::~mySQLClass()
{
	mysql_server_end();
}

int mySQLClass::Connect(char *Host, UINT Port, char *DBName, char *Account, char *PassWord)
{
	if (true == m_IsRuning)
	{
		return -1;
	}

	MYSQL *Res = mysql_real_connect(&m_SQL, Host, Account, PassWord, DBName, Port, NULL, NULL);

	if (NULL != Res)
	{
		m_IsRuning = true;

		m_Port = Port;

		memset(m_HostName, 0, sizeof(m_HostName));
		strcpy_s(m_HostName, sizeof(m_HostName), Host);
		memset(m_DBName, 0, sizeof(m_DBName));
		strcpy_s(m_DBName, sizeof(m_DBName), DBName);
		memset(m_Account, 0, sizeof(m_Account));
		strcpy_s(m_Account, sizeof(m_Account), Account);
		memset(m_Password, 0, sizeof(m_Password));
		strcpy_s(m_Password, sizeof(m_Password), PassWord);

		return 1;
	}
	else
	{
		return -1;
	}
}

int mySQLClass::Disconnect()
{
	if (false == m_IsRuning)
	{
		return -1;
	}

	mysql_close(&m_SQL);

	m_IsRuning = false;
	return 1;
}

int mySQLClass::Reconnect()
{
	Disconnect();
	Connect(m_HostName, m_Port, m_DBName, m_Account, m_Password);
	return 1;
}

int mySQLClass::RunSQL(char *SQL, bool Result /* = false */)
{
	if (0 != mysql_query(&m_SQL, SQL))
	{
		return -1;
	}

	if (true == Result)
	{
		m_DBQuery = mysql_store_result(&m_SQL);

		if (NULL == m_DBQuery)
		{
			return -1;
		}
	}

	return 1;
}

int mySQLClass::GetSQL()
{
	m_Row = mysql_fetch_row(m_DBQuery);

	if (NULL == m_Row)
	{
		return -1;
	}
	else
	{
		return 1;
	}
}

int mySQLClass::FreeSQL()
{
	mysql_free_result(m_DBQuery);
	return 1;
}

int mySQLClass::GetFieldName(UINT Id, char *Name, int nSize)
{
	m_Field = mysql_fetch_field_direct(m_DBQuery, Id);

	if (strlen(m_Field->name) > nSize)
	{
		return -1;
	}

	memcpy(Name, m_Field->name, strlen(m_Field->name));
	return 1;
}

unsigned __int64 mySQLClass::GetFieldNum()
{
	return mysql_num_fields(m_DBQuery);
}

unsigned __int64 mySQLClass::GetRowNum()
{
	return mysql_num_rows(m_DBQuery);
}

MYSQL* mySQLClass::GetSQLPoint()
{
	return &m_SQL;
}

char* mySQLClass::GetLastError()
{
	return (char*)mysql_error(&m_SQL);
}

bool mySQLClass::IsRuning()
{
	return m_IsRuning;
}

bool mySQLClass::IsActive()
{
	if (false == m_IsRuning)
	{
		return false;
	}

	if (0 != mysql_ping(&m_SQL))
	{
		return false;
	}
	else
	{
		return true;
	}
}